package com.axinfu.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化util
 *
 * @author zjn
 * @since 2022/3/23
 */
public class SerializableUtil {

    private SerializableUtil() {
    }

    /**
     * 序列化
     * 将对象转为字节数组
     *
     * @param obj 对象
     * @return 字节数组
     */
    public static byte[] obj2bytes(Object obj) {
        byte[] bytes;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
            oos.close();
            bos.close();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return bytes;
    }

    /**
     * 反序列化
     * 将字节数组转为对象
     *
     * @param bts 字节数组
     * @param <T> 对象类型
     * @return 对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T bytes2obj(byte[] bts) {
        Object obj;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bts);
            ObjectInputStream ois = new ObjectInputStream(bis);
            obj = ois.readObject();
            ois.close();
            bis.close();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return (T) obj;
    }
}
